<template>
    <div class="hospital-management">
        <h4>医院管理</h4>

        <!-- 筛选区域 -->
        <el-card class="filter-card">
            <div class="filter-container">
                <div class="filter-item">
                    <span class="filter-label">输入标题或关键字：</span>
                    <el-input v-model="filterForm.keyword" style="width: 200px" placeholder="输入标题或关键字" clearable />

                    <span class="filter-label">地区：</span>
                    <el-select v-model="filterForm.province" placeholder="请选择省份" clearable style="width: 120px"
                        @change="handleProvinceChange">
                        <el-option v-for="province in provinceData" :key="province.value" :label="province.label"
                            :value="province.value" />
                    </el-select>

                    <el-select v-model="filterForm.city" placeholder="请选择城市" clearable style="width: 120px"
                        :disabled="!filterForm.province">
                        <el-option v-for="city in cityData" :key="city.value" :label="city.label" :value="city.value" />
                    </el-select>

                    <span class="filter-label">医院等级：</span>
                    <el-select v-model="filterForm.hospitalLevel" placeholder="请选择医院等级" clearable style="width: 120px"
                        :loading="gradeLoading">
                        <el-option v-for="grade in hospitalGradeOptions" :key="grade.value" :label="grade.name"
                            :value="grade.value" />
                    </el-select>

                    <span class="filter-label">医院类型：</span>
                    <el-select v-model="filterForm.hospitalType" placeholder="请选择医院类型" clearable style="width: 120px"
                        :loading="typeLoading">
                        <el-option v-for="type in hospitalTypeOptions" :key="type.value" :label="type.name"
                            :value="type.value" />
                    </el-select>
                </div>
                <br>
                <el-button type="primary" @click="handleFilterImmediate" :loading="loading">筛选</el-button>
            </div>
        </el-card>

        <!-- 医院列表 -->
        <el-card class="list-card">
            <div class="list-header">
                <h5>医院列表</h5>
                <div class="list-actions">
                    <el-button type="success" @click="handleAdd" :disabled="loading">新增医院</el-button>
                    <el-tag v-if="loading" type="info" size="small">
                        <el-icon class="is-loading">
                            <Loading />
                        </el-icon>
                        加载中...
                    </el-tag>
                    <el-tag v-else-if="tableData.length > 0" type="success" size="small">
                        已加载 {{ tableData.length }} 条数据
                    </el-tag>
                </div>
            </div>

            <el-table ref="tableRef" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange" v-loading="loading" empty-text="暂无医院数据，请尝试调整筛选条件" :lazy="true"
                :table-layout="'auto'" :row-key="(row: any) => row.id"
                :default-sort="{ prop: 'updatedTime', order: 'descending' }">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="hospitalName" label="医院名称" width="180" />
                <el-table-column label="列表图" width="180">
                    <template #default="scope">
                        <el-image :src="scope.row.hospitalImage" :preview-src-list="[scope.row.hospitalImage]"
                            fit="cover" style="width: 80px; height: 45px; border-radius: 4px;" />
                    </template>
                </el-table-column>
                <el-table-column prop="hospitalGrade" label="医院等级" width="100">
                    <template #default="scope">
                        {{ getGradeName(scope.row.hospitalGrade) }}
                    </template>
                </el-table-column>
                <el-table-column prop="hospitalType" label="医院类型" width="100">
                    <template #default="scope">
                        {{ getTypeName(scope.row.hospitalType) }}
                    </template>
                </el-table-column>
                <el-table-column prop="createdBy" label="上传人" width="100">
                    <template #default="scope">
                        {{ scope.row.createdBy || 'admin' }}
                    </template>
                </el-table-column>
                <el-table-column prop="updatedTime" label="上传时间">
                    <template #default="scope">
                        {{ moment(scope.row.updatedTime).format('YYYY-MM-DD HH:mm:ss') }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="260">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
                        <el-button type="warning" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <div class="pagination-left">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                    <el-button type="danger" size="small" @click="handleBatchDelete"
                        :disabled="selectedRows.length === 0">批量删除</el-button>
                    <span class="pagination-info">共{{ page.pageCount }}页/{{ page.totalCount }}条数据</span>
                </div>
                <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="page.totalCount"
                    layout="total, sizes, prev, pager, next, jumper" prev-text="上一页" next-text="下一页"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增医院' : '编辑医院'" width="800px"
            @close="resetForm">
            <el-button type="primary" @click="dialogVisible = false"
                style="float: right; margin-bottom: 20px;">返回</el-button>

            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="right">
                <el-form-item label="医院名称" prop="hospitalName">
                    <el-input v-model="formData.hospitalName" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="列表图" prop="hospitalImage">
                    <el-upload class="image-upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false"
                        :on-success="handleUploadSuccess" :on-error="handleUploadError" :before-upload="beforeUpload"
                        :on-progress="handleUploadProgress" :data="uploadData" name="imageFile" accept="image/*"
                        :multiple="false" drag v-loading="uploadLoading">
                        <div class="upload-area" :class="{ 'upload-success': uploadSuccess }">
                            <el-image v-if="formData.hospitalImage" :src="formData.hospitalImage" fit="cover"
                                style="width: 100%; height: 100%; border-radius: 4px;"
                                :preview-src-list="[formData.hospitalImage]" preview-teleported />
                            <div v-else class="upload-placeholder">
                                <el-icon>
                                    <Plus />
                                </el-icon>
                                <div class="upload-text">点击上传图片</div>
                            </div>
                            <!-- 上传成功后的覆盖层 -->
                            <div v-if="formData.hospitalImage" class="upload-overlay">
                                <div class="upload-success-icon">
                                    <el-icon color="#67c23a" size="24">
                                        <Check />
                                    </el-icon>
                                </div>
                            </div>
                            <!-- 上传成功提示 -->
                            <div v-if="uploadSuccess" class="upload-success-message">
                                <el-icon color="#67c23a" size="20">
                                    <Check />
                                </el-icon>
                                <span>上传成功</span>
                            </div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">建议尺寸120*90像素，大小不要超过1M</div>
                    <!-- 图片信息显示 -->
                    <div v-if="formData.hospitalImage" class="image-info">
                        <el-tag size="small" type="success">已上传</el-tag>
                        <el-button size="small" type="primary" @click="reuploadImage">重新上传</el-button>
                    </div>
                    <!-- 上传历史 -->
                    <div v-if="uploadHistory.length > 0" class="upload-history">
                        <div class="history-title">最近上传的图片：</div>
                        <div class="history-list">
                            <div v-for="(url, index) in uploadHistory" :key="index" class="history-item">
                                <el-image :src="url" style="width: 60px; height: 34px; border-radius: 4px;"
                                    fit="cover" />
                                <el-button size="small" @click="selectHistoryImage(url)">选择</el-button>
                            </div>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="医院等级" prop="hospitalGrade">
                    <el-select v-model="formData.hospitalGrade" placeholder="请选择医院等级" style="width: 200px;"
                        :loading="gradeLoading" :disabled="gradeLoading">
                        <el-option v-for="grade in hospitalGradeOptions" :key="grade.value" :label="grade.name"
                            :value="grade.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="医院类型" prop="hospitalType">
                    <el-select v-model="formData.hospitalType" placeholder="请选择医院类型" style="width: 200px;"
                        :loading="typeLoading" :disabled="typeLoading">
                        <el-option v-for="type in hospitalTypeOptions" :key="type.value" :label="type.name"
                            :value="type.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="是否推荐" prop="isRecommend">
                    <el-radio-group v-model="formData.isRecommend">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="医生人数" prop="doctorsNum">
                    <el-input-number v-model="formData.doctorsNum" :min="0" placeholder="请输入" style="width: 200px;" />
                </el-form-item>

                <el-form-item label="科室数" prop="departmentsNum">
                    <el-input-number v-model="formData.departmentsNum" :min="0" placeholder="请输入"
                        style="width: 200px;" />
                </el-form-item>

                <el-form-item label="医院科室" prop="departments">
                    <div class="department-selection" v-loading="departmentLoading">
                        <div class="department-left">
                            <div v-if="departmentLoading" class="loading-text">
                                正在加载科室信息...
                            </div>
                            <el-checkbox-group v-else v-model="selectedDepartments">
                                <el-checkbox v-for="dept in departmentOptions" :key="dept.id"
                                    :label="dept.departmentName">
                                    {{ dept.departmentName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                        <div class="department-arrow">
                            <el-icon>
                                <ArrowRight />
                            </el-icon>
                        </div>
                        <div class="department-right">
                            <el-input v-model="selectedDepartmentsText" type="textarea" :rows="8"
                                placeholder="选中的科室将显示在这里" readonly />
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="所在地区" prop="location">
                    <el-select v-model="formData.province" placeholder="请选择省份" style="width: 150px; margin-right: 10px;"
                        @change="handleProvinceChange">
                        <el-option v-for="province in provinceData" :key="province.value" :label="province.label"
                            :value="province.value" />
                    </el-select>
                    <el-select v-model="formData.city" placeholder="请选择城市" style="width: 150px;"
                        :disabled="!formData.province">
                        <el-option v-for="city in cityData" :key="city.value" :label="city.label" :value="city.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="详细地址" prop="hospitalAddress">
                    <el-input v-model="formData.hospitalAddress" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="医院电话" prop="hospitalPhone">
                    <el-input v-model="formData.hospitalPhone" placeholder="请输入" />
                </el-form-item>

                <el-form-item label="医院介绍" prop="hospitalIntroduction">
                    <div class="rich-text-editor" v-if="dialogVisible">
                        <!-- 工具栏 -->
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" mode="default" />
                        <!-- 编辑器 -->
                        <Editor style="height: 300px; overflow-y: hidden;" v-model="valueHtml"
                            :defaultConfig="editorConfig" mode="default" @onCreated="handleCreated" />
                    </div>
                    <div v-else class="editor-placeholder">
                        <p style="color: #909399; font-size: 14px; padding: 20px; text-align: center;">
                            富文本编辑器将在对话框打开时加载
                        </p>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 医院详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="医院详情" width="900px">
            <el-button type="primary" @click="detailDialogVisible = false"
                style="float: right; margin-bottom: 20px;">返回</el-button>

            <div class="hospital-detail">
                <div class="detail-section">
                    <h3>基本信息</h3>
                    <div class="detail-content">
                        <div class="detail-left">
                            <el-image :src="currentHospital.hospitalImage"
                                style="width: 200px; height: 150px; border-radius: 8px;" fit="cover" />
                        </div>
                        <div class="detail-right">
                            <table class="detail-table">

                                <body>
                                    <tr>
                                        <td class="label">ID</td>
                                        <td>{{ currentHospital.id || '01' }}</td>
                                        <td class="label">医院名称</td>
                                        <td>{{ currentHospital.hospitalName }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">医院等级</td>
                                        <td>{{ getGradeName(currentHospital.hospitalGrade) }}</td>
                                        <td class="label">医院类型</td>
                                        <td>{{ getTypeName(currentHospital.hospitalType) }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">是否推荐</td>
                                        <td>{{ currentHospital.isRecommend ? '是' : '否' }}</td>
                                        <td class="label">医生人数</td>
                                        <td>{{ currentHospital.doctorsNum }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">科室数</td>
                                        <td>{{ currentHospital.departmentsNum }}</td>
                                        <td class="label">所在地区</td>
                                        <td>{{ currentHospital.inTheArea || (currentHospital.province ?
                                            codeToText[currentHospital.province] : '') + (currentHospital.city ?
                                                codeToText[currentHospital.city] : '') }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">详细地址</td>
                                        <td colspan="3">{{ currentHospital.hospitalAddress }}</td>
                                    </tr>
                                    <tr>
                                        <td class="label">医院电话</td>
                                        <td colspan="3">{{ currentHospital.hospitalPhone }}</td>
                                    </tr>
                                </body>

                            </table>
                        </div>
                    </div>
                </div>

                <div class="detail-section">
                    <h3>科室</h3>
                    <div class="department-list">
                        <div class="department-category">
                            <h4>医院科室</h4>
                            <div class="department-items">
                                <span
                                    v-for="dept in (currentHospital.hospitalDepartments || '').split(',').filter((d: string) => d.trim())"
                                    :key="dept" class="department-tag">
                                    {{ dept.trim() }}
                                </span>
                                <span v-if="!(currentHospital.hospitalDepartments || '').trim()" class="no-department">
                                    暂无科室信息
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="detail-section">
                    <h3>简介</h3>
                    <div class="hospital-intro">
                        <div v-if="currentHospital.hospitalIntroduction" v-html="currentHospital.hospitalIntroduction"
                            class="rich-content">
                        </div>
                        <div v-else class="default-intro">
                            <p>北京协和医院是一所位于北京市东城区，集医疗、科研、教学为一体的大型综合医院。它隶属于中国协和医科大学(2006年改名为北京协和医学院/清华大学医学部)，是卫生部直属医院，同时也是中国医学科学院临床医学研究所，中华人民共和国卫生部指定的诊治疑难重症的技术指导中心之一。北京协和医院在中国乃至世界享有盛名，医院成立于1921年，现任院长赵玉沛。北京协和医院是中国最早承担外宾医疗任务的单位，医院专门设立了外宾和高干门诊部，开设了VIP病房，外宾、特需病区。2006年7月28日被中国奥委会全会确定为"国家队运动员医疗服务指定医院"。
                            </p>
                            <p>2017年11月11日下午，复旦大学医院管理研究所正式发布了《2016年度中国医院排行榜》和《2016年度中国医院专科声誉排行榜》，北京协和医院名列榜首[1]。</p>
                            <p>2018年12月4日消息，被国家卫健委公布首批肿瘤多学科诊疗试点医院。[2] 2019年11月10日，复旦版《2018年度中国最佳医院综合排行榜》发布，北京协和医院位列第一。
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, onBeforeUnmount, shallowRef, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, ArrowRight, Check, Loading } from '@element-plus/icons-vue'
import { readB, writeB } from '@/api/http'
import moment from 'moment'
import { regionData, codeToText } from 'element-china-area-data'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { createEditor, createToolbar } from '@wangeditor/editor'
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 响应式数据 - 医院列表数据将从API动态获取
const tableData = ref<any[]>([])

const loading = ref(false)
const submitLoading = ref(false)
const uploadLoading = ref(false)
const uploadSuccess = ref(false)
const uploadHistory = ref<string[]>([])
const dialogVisible = ref(false)

// 富文本编辑器相关
const editorRef = shallowRef()
const valueHtml = ref('')
const editorInitialized = ref(false)

// 工具栏配置
const toolbarConfig = {
    // 隐藏某些菜单
    excludeKeys: [
        'group-video', // 排除视频
        'insertVideo',
        'uploadVideo',
        'group-image', // 保留图片功能但简化
        'codeBlock', // 排除代码块
        'group-indent' // 排除缩进
    ]
}

// 编辑器配置
const editorConfig = {
    placeholder: '请输入医院介绍...',
    MENU_CONF: {
        // 配置上传图片
        uploadImage: {
            server: 'http://localhost:5023/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=hospital',
            fieldName: 'imageFile',
            meta: {
                bucketName: 'image',
                prefix: 'hospital'
            },
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
            },
            // 上传成功回调
            onSuccess(file: any, res: any) {
                console.log('富文本图片上传成功', file, res)
            },
            // 上传失败回调
            onFailed(file: any, res: any) {
                console.log('富文本图片上传失败', file, res)
                ElMessage.error('图片上传失败')
            },
            // 上传错误回调
            onError(file: any, err: any, res: any) {
                console.log('富文本图片上传错误', file, err, res)
                ElMessage.error('图片上传出错')
            }
        }
    }
}
const detailDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const tableRef = ref()
const selectedRows = ref<any[]>([])
const selectAll = ref(false)
const currentHospital = ref<any>({})

// 省市联动数据
const provinceData = ref(regionData)
const cityData = ref<any[]>([])

// 筛选表单
const filterForm = reactive({
    keyword: '',
    province: '',
    city: '',
    hospitalLevel: '',
    hospitalType: ''
})

// 分页参数
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    pageCount: 0
})

// 表单数据
const formData = reactive({
    id: '',
    hospitalName: '',
    hospitalImage: '',
    hospitalGrade: 0, // 医院等级（数字）
    hospitalType: 0, // 医院类型（数字）
    isRecommend: false, // 是否推荐
    doctorsNum: 0, // 医生人数（数字）
    departmentsNum: 0, // 科室数（数字）
    hospitalDepartments: '', // 医院科室（字符串）
    hospitalAddress: '', // 医院地址
    hospitalPhone: '', // 医院电话
    inTheArea: '', // 所在地区
    hospitalIntroduction: '', // 医院介绍
    province: '', // 临时存储省份（用于界面显示）
    city: '' // 临时存储城市（用于界面显示）
})

// 医院等级和类型数据（动态获取）
const hospitalGradeOptions = ref<Array<{ name: string, value: number }>>([])
const hospitalTypeOptions = ref<Array<{ name: string, value: number }>>([])

// 医院科室数据（动态获取）
const departmentOptions = ref<Array<{ departmentName: string, id: number }>>([])

// 医院等级、类型和科室加载状态
const gradeLoading = ref(false)
const typeLoading = ref(false)
const departmentLoading = ref(false)

// 科室选择
const selectedDepartments = ref([])

// 计算选中科室的文本
const selectedDepartmentsText = computed(() => {
    return selectedDepartments.value.join('\n')
})

// 检查基础数据是否已加载完成
const isDataReady = computed(() => {
    return !gradeLoading.value && !typeLoading.value && !departmentLoading.value &&
        hospitalGradeOptions.value.length > 0 &&
        hospitalTypeOptions.value.length > 0 &&
        departmentOptions.value.length > 0
})

// 监听科室变化，更新表单数据
watch(() => selectedDepartments.value, (newVal) => {
    formData.hospitalDepartments = newVal.join(',')
})

// 监听富文本内容变化
watch(() => valueHtml.value, (newVal) => {
    formData.hospitalIntroduction = newVal
})

// 监听表单数据变化，同步到富文本编辑器
watch(() => formData.hospitalIntroduction, (newVal) => {
    if (newVal !== valueHtml.value) {
        valueHtml.value = newVal || ''
    }
})

// 监听省市变化，更新地区字段
watch([() => formData.province, () => formData.city], ([province, city]) => {
    if (province && city) {
        const provinceName = codeToText[province] || ''
        const cityName = codeToText[city] || ''
        formData.inTheArea = provinceName + cityName
    } else {
        formData.inTheArea = ''
    }
})

// 获取医院等级名称
const getGradeName = (gradeValue: number | undefined): string => {
    if (gradeValue === undefined || gradeValue === null) return '未设置'
    if (gradeLoading.value) return '加载中...'

    // 如果数据还没有加载完成，但有默认值，则使用默认映射
    if (hospitalGradeOptions.value.length === 0) {
        const defaultGrades = ['三甲', '三乙', '二甲', '二乙', '一甲', '一乙', '未评级']
        return defaultGrades[gradeValue] || `等级${gradeValue}`
    }

    const grade = hospitalGradeOptions.value.find(item => item.value === gradeValue)
    return grade?.name || `等级${gradeValue}`
}

// 获取医院类型名称
const getTypeName = (typeValue: number | undefined): string => {
    if (typeValue === undefined || typeValue === null) return '未设置'
    if (typeLoading.value) return '加载中...'

    // 如果数据还没有加载完成，但有默认值，则使用默认映射
    if (hospitalTypeOptions.value.length === 0) {
        const defaultTypes = ['综合医院', '专科医院', '中医医院', '中西医结合医院', '妇幼保健院',
            '儿童医院', '肿瘤医院', '传染病医院', '精神病医院', '康复医院', '护理院', '其他']
        return defaultTypes[typeValue] || `类型${typeValue}`
    }

    const type = hospitalTypeOptions.value.find(item => item.value === typeValue)
    return type?.name || `类型${typeValue}`
}

// 表单验证规则
const formRules: FormRules = {
    hospitalName: [
        { required: true, message: '请输入医院名称', trigger: 'blur' }
    ],
    hospitalImage: [
        { required: true, message: '请上传医院图片', trigger: 'change' }
    ],
    hospitalGrade: [
        { required: true, message: '请选择医院等级', trigger: 'change' }
    ],
    hospitalType: [
        { required: true, message: '请选择医院类型', trigger: 'change' }
    ],
    doctorsNum: [
        { required: true, message: '请输入医生人数', trigger: 'blur' },
        { type: 'number', message: '医生人数必须为数字', trigger: 'blur' }
    ],
    departmentsNum: [
        { required: true, message: '请输入科室数', trigger: 'blur' },
        { type: 'number', message: '科室数必须为数字', trigger: 'blur' }
    ],
    province: [
        { required: true, message: '请选择省份', trigger: 'change' }
    ],
    hospitalAddress: [
        { required: true, message: '请输入详细地址', trigger: 'blur' }
    ],
    hospitalPhone: [
        { required: true, message: '请输入医院电话', trigger: 'blur' }
    ]
}

// 省市联动方法
const handleProvinceChange = (provinceCode: string) => {
    // 清空城市选择
    filterForm.city = ''
    formData.city = ''

    if (provinceCode) {
        // 根据省份代码获取对应的城市数据
        const province = provinceData.value.find((item: any) => item.value === provinceCode)
        if (province && province.children) {
            cityData.value = province.children
        } else {
            cityData.value = []
        }
    } else {
        cityData.value = []
    }
}

// 监听筛选条件变化，自动触发筛选
watch(() => filterForm.keyword, (newVal, oldVal) => {
    if (newVal !== oldVal) {
        handleFilter() // 使用防抖筛选
    }
})

// 监听省份变化
watch(() => filterForm.province, (newVal) => {
    handleProvinceChange(newVal)
})

watch(() => formData.province, (newVal) => {
    handleProvinceChange(newVal)
})

// 上传相关
const uploadUrl = 'http://47.95.68.41:4560/api/Carousel/UploadCarouselImage/upload-image?bucketName=image&prefix=hospital'
const uploadHeaders = {
    'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
}
const uploadData = {
    bucketName: 'images',
    prefix: 'hospital'
}

// 获取医院等级
const getHospitalLevels = async () => {
    gradeLoading.value = true
    try {
        const res = await readB.get('/api/Hospital/GetHospitalLevels/levels')
        if (res.data.code === 200) {
            hospitalGradeOptions.value = res.data.data || []
            console.log('医院等级获取成功:', hospitalGradeOptions.value)
        } else {
            ElMessage.error(res.data.message || '获取医院等级失败')

        }
    } catch (error) {
        console.error('获取医院等级失败:', error)
        ElMessage.error('获取医院等级失败')

    } finally {
        gradeLoading.value = false
    }
}

// 获取医院类型
const getHospitalTypes = async () => {
    typeLoading.value = true
    try {
        const res = await readB.get('/api/Hospital/GetHospitalTypes/types')
        if (res.data.code === 200) {
            hospitalTypeOptions.value = res.data.data || []
            console.log('医院类型获取成功:', hospitalTypeOptions.value)
        } else {
            ElMessage.error(res.data.message || '获取医院类型失败')
        }
    } catch (error) {
        console.error('获取医院类型失败:', error)
        ElMessage.error('获取医院类型失败')
    } finally {
        typeLoading.value = false
    }
}

// 获取医院科室
const getAllDepartments = async () => {
    departmentLoading.value = true
    try {
        const res = await readB.get('/api/Department/GetAllDepartments/all')
        if (res.data.code === 200) {
            departmentOptions.value = res.data.data || []
            console.log('医院科室获取成功:', departmentOptions.value)
        } else {
            ElMessage.error(res.data.message || '获取医院科室失败')

        }
    } catch (error) {

        ElMessage.error('获取医院科室失败')

    } finally {
        departmentLoading.value = false
    }
}

// 获取医院列表
const getHospitalList = async () => {
    loading.value = true
    try {
        // 构建地区参数
        let inTheArea = ''
        if (filterForm.province && filterForm.city) {
            const provinceName = codeToText[filterForm.province] || ''
            const cityName = codeToText[filterForm.city] || ''
            inTheArea = provinceName + cityName
        } else if (filterForm.province) {
            inTheArea = codeToText[filterForm.province] || ''
        }

        // 调用真实API
        const res = await readB.get('/api/Hospital/GetHospitalList/list', {
            params: {
                PageIndex: page.PageIndex,
                PageSize: page.PageSize,
                HospitalName: filterForm.keyword || undefined,
                HospitalGrade: filterForm.hospitalLevel || undefined,
                HospitalType: filterForm.hospitalType || undefined,
                InTheArea: inTheArea || undefined
            }
        })

        if (res.data.code === 200) {
            // 更新医院列表数据
            tableData.value = res.data.data || []
            // 更新分页信息
            page.totalCount = res.data.totalCount || 0
            page.pageCount = Math.ceil(page.totalCount / page.PageSize)

            // 清空选择状态（新数据加载后重置选择）
            selectedRows.value = []
            selectAll.value = false
            if (tableRef.value) {
                tableRef.value.clearSelection()
            }
        } else {
            ElMessage.error(res.data.message || '获取医院列表失败')
            console.error('API返回错误:', res.data)
        }
    } catch (error) {
        console.error('获取医院列表失败:', error)
        ElMessage.error('获取数据失败，请检查网络连接')
        // 发生错误时保持现有数据，不清空列表
    } finally {
        loading.value = false
    }
}

// 防抖定时器
let filterDebounceTimer: number | null = null

// 筛选处理 - 添加防抖机制
const handleFilter = () => {
    if (filterDebounceTimer) {
        clearTimeout(filterDebounceTimer)
    }

    filterDebounceTimer = setTimeout(() => {
        page.PageIndex = 1
        getHospitalList()
    }, 300) // 300ms 防抖延迟
}

// 立即筛选（用于按钮点击）
const handleFilterImmediate = () => {
    if (filterDebounceTimer) {
        clearTimeout(filterDebounceTimer)
    }
    page.PageIndex = 1
    getHospitalList()
}

// 选择处理
const handleSelectionChange = (rows: any[]) => {
    selectedRows.value = rows
    selectAll.value = rows.length === tableData.value.length && tableData.value.length > 0
}

// 全选处理
const handleSelectAll = (checked: boolean) => {
    if (!tableRef.value) return

    if (checked) {
        // 全选：选中所有行
        tableData.value.forEach(row => {
            tableRef.value.toggleRowSelection(row, true)
        })
        selectedRows.value = [...tableData.value]
        console.log('全选操作:', selectedRows.value.length, '条数据')
    } else {
        // 取消全选：清空所有选中
        tableRef.value.clearSelection()
        selectedRows.value = []
        console.log('取消全选操作')
    }
}

// 分页处理
const handleSizeChange = (size: number) => {
    page.PageSize = size
    page.PageIndex = 1
    getHospitalList()
}

const handleCurrentChange = (current: number) => {
    page.PageIndex = current
    getHospitalList()
}

// 新增医院
const handleAdd = () => {
    dialogType.value = 'add'
    dialogVisible.value = true
    resetForm()
    // 延迟初始化编辑器
    nextTick(() => {
        initEditorWhenNeeded()
    })
}

// 编辑医院
const handleEdit = (row: any) => {
    dialogType.value = 'edit'
    dialogVisible.value = true

    // 映射后端数据到表单字段
    Object.assign(formData, {
        id: row.id,
        hospitalName: row.hospitalName,
        hospitalImage: row.hospitalImage,
        hospitalGrade: row.hospitalGrade || 0,
        hospitalType: row.hospitalType || 0,
        isRecommend: row.isRecommend || false,
        doctorsNum: row.doctorsNum || 0,
        departmentsNum: row.departmentsNum || 0,
        hospitalDepartments: row.hospitalDepartments || '',
        hospitalAddress: row.hospitalAddress || '',
        hospitalPhone: row.hospitalPhone || '',
        inTheArea: row.inTheArea || '',
        hospitalIntroduction: row.hospitalIntroduction || '',
        province: row.province || '',
        city: row.city || ''
    })

    // 设置选中的科室
    if (row.hospitalDepartments) {
        selectedDepartments.value = row.hospitalDepartments.split(',').filter((dept: string) => dept.trim())
    } else {
        selectedDepartments.value = []
    }

    // 延迟初始化编辑器并设置内容
    nextTick(() => {
        initEditorWhenNeeded()
        // 同步富文本编辑器内容
        valueHtml.value = row.hospitalIntroduction || ''
    })

    // 如果有省份信息，需要加载对应的城市数据
    if (formData.province) {
        handleProvinceChange(formData.province)
    }
}

// 查看详情
const handleViewDetail = (row: any) => {
    currentHospital.value = { ...row }
    detailDialogVisible.value = true
}

// 删除医院
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(`确定要删除医院 "${row.hospitalName}" 吗？`, '删除确认', {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false
        })

        // 调用批量删除API，传递单个医院ID
        const deleteData = {
            hospitalIds: [row.id]
        }

        console.log('删除医院数据:', deleteData)

        const res = await writeB.post('/api/Hospital/BatchDeleteHospital/batch-delete', deleteData)

        if (res.data.code === 200) {
            ElMessage.success(`医院 "${row.hospitalName}" 删除成功`)
            // 刷新医院列表
            getHospitalList()
            console.log('医院删除成功:', res.data)
        } else {
            ElMessage.error(res.data.message || '删除失败')
            console.error('医院删除失败:', res.data)
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除医院失败:', error)
            ElMessage.error('删除失败，请检查网络连接')
        }
    }
}

// 批量删除
const handleBatchDelete = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的医院')
        return
    }

    try {
        const hospitalNames = selectedRows.value.map(row => row.hospitalName).join('、')
        const confirmMessage = selectedRows.value.length > 3
            ? `确定要删除选中的 ${selectedRows.value.length} 个医院吗？`
            : `确定要删除以下医院吗？\n${hospitalNames}`

        await ElMessageBox.confirm(confirmMessage, '批量删除确认', {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: false
        })

        // 提取医院ID列表
        const hospitalIds = selectedRows.value.map(row => row.id)
        const deleteData = {
            hospitalIds: hospitalIds
        }

        console.log('批量删除医院数据:', deleteData)

        const res = await writeB.post('/api/Hospital/BatchDeleteHospital/batch-delete', deleteData)

        if (res.data.code === 200) {
            ElMessage.success(`成功删除 ${selectedRows.value.length} 个医院`)
            // 清空选中行
            selectedRows.value = []
            selectAll.value = false
            // 刷新医院列表
            getHospitalList()
            console.log('批量删除成功:', res.data)
        } else {
            ElMessage.error(res.data.message || '批量删除失败')
            console.error('批量删除失败:', res.data)
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('批量删除医院失败:', error)
            ElMessage.error('批量删除失败，请检查网络连接')
        }
    }
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return
    try {
        await formRef.value.validate()
        submitLoading.value = true

        // 准备提交数据，按照API接口要求的格式
        const submitData = {
            hospitalName: formData.hospitalName,
            hospitalImage: formData.hospitalImage,
            hospitalGrade: formData.hospitalGrade,
            hospitalType: formData.hospitalType,
            isRecommend: formData.isRecommend,
            doctorsNum: formData.doctorsNum,
            departmentsNum: formData.departmentsNum,
            hospitalDepartments: formData.hospitalDepartments,
            hospitalAddress: formData.hospitalAddress,
            hospitalPhone: formData.hospitalPhone,
            inTheArea: formData.inTheArea,
            hospitalIntroduction: formData.hospitalIntroduction
        }

        console.log('提交数据:', submitData)

        if (dialogType.value === 'add') {
            // 新增医院
            const res = await writeB.post('/api/Hospital/AddHospital/add', submitData)
            if (res.data.code === 200) {
                ElMessage.success('新增成功')
                dialogVisible.value = false
                getHospitalList()
            } else {
                ElMessage.error(res.data.message || '新增失败')
            }
        } else {
            // 编辑医院 - 按照API接口要求添加ID
            const updateData = {
                id: formData.id,
                hospitalName: formData.hospitalName,
                hospitalImage: formData.hospitalImage,
                hospitalGrade: formData.hospitalGrade,
                hospitalType: formData.hospitalType,
                isRecommend: formData.isRecommend,
                doctorsNum: formData.doctorsNum,
                departmentsNum: formData.departmentsNum,
                hospitalDepartments: formData.hospitalDepartments,
                hospitalAddress: formData.hospitalAddress,
                hospitalPhone: formData.hospitalPhone,
                inTheArea: formData.inTheArea,
                hospitalIntroduction: formData.hospitalIntroduction
            }

            console.log('更新医院数据:', updateData)

            const res = await writeB.put('/api/Hospital/UpdateHospital/update', updateData)
            if (res.data.code === 200) {
                ElMessage.success('医院信息更新成功')
                dialogVisible.value = false
                // 刷新医院列表
                getHospitalList()
                console.log('医院更新成功:', res.data)
            } else {
                ElMessage.error(res.data.message || '更新失败')
                console.error('医院更新失败:', res.data)
            }
        }
    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败，请检查网络连接')
    } finally {
        submitLoading.value = false
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.assign(formData, {
        id: '',
        hospitalName: '',
        hospitalImage: '',
        hospitalGrade: 0,
        hospitalType: 0,
        isRecommend: false,
        doctorsNum: 0,
        departmentsNum: 0,
        hospitalDepartments: '',
        hospitalAddress: '',
        hospitalPhone: '',
        inTheArea: '',
        hospitalIntroduction: '',
        province: '',
        city: ''
    })
    selectedDepartments.value = []
    // 清空上传状态
    uploadSuccess.value = false
    // 清空富文本编辑器内容
    valueHtml.value = ''
    // 清空城市数据
    cityData.value = []
}

// 上传相关方法
const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith('image/')
    const isLt1M = file.size / 1024 / 1024 < 1

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt1M) {
        ElMessage.error('图片大小不能超过 1MB!')
        return false
    }

    uploadLoading.value = true
    return true
}

const handleUploadSuccess = (response: any) => {
    console.log('医院图片上传响应:', response)
    uploadLoading.value = false

    if (response.code === 200) {
        // 根据轮播图上传API响应格式处理图片URL
        const imageUrl = response.data?.url || response.data || response
        formData.hospitalImage = imageUrl

        // 添加到上传历史
        uploadHistory.value.unshift(imageUrl)
        if (uploadHistory.value.length > 5) {
            uploadHistory.value.pop()
        }

        // 显示上传成功状态
        uploadSuccess.value = true
        setTimeout(() => {
            uploadSuccess.value = false
        }, 2000)

        ElMessage.success('图片上传成功')
        console.log('图片URL设置为:', imageUrl)
    } else {
        ElMessage.error(response.message || '上传失败')
        console.error('上传失败响应:', response)
    }
}

const handleUploadError = (error: any) => {
    console.error('医院图片上传错误:', error)
    uploadLoading.value = false
    ElMessage.error('上传失败，请检查网络连接或文件格式')
}

const handleUploadProgress = (event: any) => {
    console.log('上传进度:', event.percent)
}

// 重新上传图片
const reuploadImage = () => {
    formData.hospitalImage = ''
    ElMessage.info('请重新选择图片上传')
}

// 选择历史图片
const selectHistoryImage = (url: string) => {
    formData.hospitalImage = url
    ElMessage.success('已选择历史图片')
}

// 富文本编辑器处理方法
const handleCreated = (editor: any) => {
    editorRef.value = editor
    editorInitialized.value = true
    console.log('富文本编辑器创建成功', editor)
}

// 延迟初始化编辑器
const initEditorWhenNeeded = () => {
    if (!editorInitialized.value) {
        // 编辑器会在模板渲染时自动初始化
        console.log('准备初始化富文本编辑器')
    }
}

// 组件销毁时的清理工作
onBeforeUnmount(() => {
    // 销毁富文本编辑器
    const editor = editorRef.value
    if (editor) {
        editor.destroy()
    }

    // 清理防抖定时器
    if (filterDebounceTimer) {
        clearTimeout(filterDebounceTimer)
        filterDebounceTimer = null
    }
})

// 基础数据缓存
const baseDataCache = ref<{
    levels: Array<{ name: string, value: number }> | null,
    types: Array<{ name: string, value: number }> | null,
    departments: Array<{ departmentName: string, id: number }> | null,
    timestamp: number
}>({
    levels: null,
    types: null,
    departments: null,
    timestamp: 0
})

// 缓存过期时间（5分钟）
const CACHE_EXPIRE_TIME = 5 * 60 * 1000

// 检查缓存是否有效
const isCacheValid = () => {
    return Date.now() - baseDataCache.value.timestamp < CACHE_EXPIRE_TIME
}

// 生命周期
onMounted(async () => {
    // 并行加载医院列表和基础数据，提升加载速度
    await Promise.all([
        getHospitalList(), // 医院列表可以先加载
        loadBaseDataWithCache() // 基础数据使用缓存机制
    ])
})

// 带缓存的基础数据加载
const loadBaseDataWithCache = async () => {
    // 检查是否有有效缓存
    if (baseDataCache.value.levels && baseDataCache.value.types &&
        baseDataCache.value.departments && isCacheValid()) {
        // 使用缓存数据
        hospitalGradeOptions.value = baseDataCache.value.levels
        hospitalTypeOptions.value = baseDataCache.value.types
        departmentOptions.value = baseDataCache.value.departments
        console.log('使用缓存数据')
        return
    }

    // 并行获取基础数据
    try {
        const [levels, types, departments] = await Promise.all([
            getHospitalLevels(),
            getHospitalTypes(),
            getAllDepartments()
        ])

        // 更新缓存
        baseDataCache.value = {
            levels: hospitalGradeOptions.value,
            types: hospitalTypeOptions.value,
            departments: departmentOptions.value,
            timestamp: Date.now()
        }
        console.log('基础数据已缓存')
    } catch (error) {
        console.error('加载基础数据失败:', error)
    }
}
</script>

<style scoped>
.hospital-management {
    padding: 20px;
}

.filter-card {
    margin-bottom: 20px;
}

.filter-container {
    display: flex;
    align-items: center;
    gap: 20px;
    flex-wrap: wrap;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-label {
    white-space: nowrap;
    font-weight: 500;
}

.list-card {
    margin-top: 20px;
}

.list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.list-header h5 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.list-actions {
    display: flex;
    gap: 10px;
    align-items: center;
}

.editor-placeholder {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background-color: #f5f7fa;
    min-height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.pagination-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.pagination-info {
    color: #606266;
    font-size: 14px;
}

.image-upload {
    width: 100%;
}

.upload-area {
    width: 120px;
    height: 90px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
}

.upload-area:hover {
    border-color: #409eff;
}

.upload-area.is-dragover {
    border-color: #409eff;
    background-color: #f0f9ff;
}

.upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    opacity: 0;
    transition: opacity 0.3s;
}

.upload-area:hover .upload-overlay {
    opacity: 1;
}

.upload-success-icon {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.upload-success {
    border-color: #67c23a !important;
    box-shadow: 0 0 10px rgba(103, 194, 58, 0.3);
}

.upload-success-message {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(103, 194, 58, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #8c939d;
}

.upload-placeholder .el-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

.image-info {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 12px;
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.image-url {
    font-size: 12px;
    color: #606266;
    word-break: break-all;
    flex: 1;
}

.upload-history {
    margin-top: 12px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.history-title {
    font-size: 14px;
    font-weight: 500;
    color: #495057;
    margin-bottom: 8px;
}

.history-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.history-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px;
    background: white;
    border-radius: 4px;
    border: 1px solid #dee2e6;
}

.history-url {
    font-size: 12px;
    color: #6c757d;
    flex: 1;
    word-break: break-all;
}

/* 富文本编辑器样式 */
.rich-text-editor {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

.rich-text-editor:hover {
    border-color: #c0c4cc;
}

.rich-text-editor:focus-within {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.department-selection {
    display: flex;
    gap: 20px;
    align-items: flex-start;
}

.department-left {
    flex: 1;
}

.department-left .el-checkbox {
    display: block;
    margin-bottom: 8px;
}

.loading-text {
    color: #909399;
    font-size: 14px;
    text-align: center;
    padding: 20px;
    margin: 10px 0;
}

.department-arrow {
    font-size: 24px;
    color: #409eff;
    margin-top: 60px;
}

.department-right {
    flex: 1;
}

.editor-toolbar {
    margin-bottom: 8px;
}

.dialog-footer {
    text-align: right;
}

/* 详情页样式 */
.hospital-detail {
    padding: 20px;
}

.detail-section {
    margin-bottom: 30px;
}

.detail-section h3 {
    color: #333;
    font-size: 18px;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 2px solid #f0f0f0;
}

.detail-content {
    display: flex;
    gap: 20px;
}

.detail-left {
    flex-shrink: 0;
}

.detail-right {
    flex: 1;
}

.detail-table {
    width: 100%;
    border-collapse: collapse;
}

.detail-table td {
    padding: 8px 12px;
    border: 1px solid #e4e7ed;
    font-size: 14px;
}

.detail-table .label {
    background-color: #f5f7fa;
    font-weight: 500;
    width: 100px;
}

.department-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.department-category h4 {
    margin: 0 0 10px 0;
    font-size: 16px;
    color: #333;
}

.department-items {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.department-tag {
    padding: 4px 8px;
    background-color: #f0f9ff;
    color: #1890ff;
    border-radius: 4px;
    font-size: 12px;
    border: 1px solid #d4edda;
}

.no-department {
    color: #909399;
    font-size: 14px;
    font-style: italic;
    padding: 8px;
}

.hospital-intro {
    line-height: 1.6;
    color: #666;
}

.hospital-intro p {
    margin-bottom: 15px;
}

/* 富文本内容样式 */
.rich-content {
    line-height: 1.6;
    color: #666;
}

.rich-content p {
    margin-bottom: 15px;
    margin-top: 0;
}

.rich-content h1,
.rich-content h2,
.rich-content h3,
.rich-content h4,
.rich-content h5,
.rich-content h6 {
    margin-top: 20px;
    margin-bottom: 10px;
    color: #333;
}

.rich-content ul,
.rich-content ol {
    margin-bottom: 15px;
    padding-left: 20px;
}

.rich-content img {
    max-width: 100%;
    height: auto;
    border-radius: 4px;
    margin: 10px 0;
}

.rich-content blockquote {
    margin: 15px 0;
    padding: 10px 15px;
    background-color: #f8f9fa;
    border-left: 4px solid #409eff;
    color: #666;
}

.rich-content code {
    background-color: #f1f2f3;
    padding: 2px 4px;
    border-radius: 3px;
    font-family: monospace;
    color: #e74c3c;
}

.rich-content pre {
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 15px 0;
}

.rich-content a {
    color: #409eff;
    text-decoration: none;
}

.rich-content a:hover {
    text-decoration: underline;
}

.default-intro p {
    margin-bottom: 15px;
    margin-top: 0;
}
</style>